﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasker.Composition;
using Tasker.Infrastructure.Entities;
using Tasker.Infrastructure.Repositories;
using Tasker.Infrastructure.Repositories.Base;
using Tasker.Repositories.Entities;

namespace Tasker.Repositories
{
    public class TaskWorkersRepositoryEF: ITaskWorkersRepository
    {
        private EntitiesContext _context = Resolver.Resolve<EntitiesContext>();
        private IContextManager _manager = Resolver.Resolve<IContextManager>();

        public ITaskWorker SelectById(int id)
        {
            return _context.TaskWorkers.SingleOrDefault(tw => tw.Id == id);
        }

        public IEnumerable<ITaskWorker> SelectByUserId(int userId)
        {
            return _context.TaskWorkers.Where(tw => tw.UserId == userId);
        }

        public IEnumerable<ITaskWorker> SelectByTaskId(int taskId)
        {
            return _context.TaskWorkers.Where(tw => tw.TaskId == taskId);
        }

        public void DeleteAll(int taskId)
        {
            IEnumerable<TaskWorker> taskWorkers = _context.TaskWorkers.Where(tw => tw.TaskId == taskId);
            foreach (TaskWorker taskWorker in taskWorkers)
            {
                _context.TaskWorkers.DeleteObject(taskWorker);
            }
        }

        public IEnumerable<ITaskWorker> SelectAll()
        {
            return _context.TaskWorkers.ToList();
        }

        public void Update(ITaskWorker entity)
        {
            throw new NotImplementedException();
        }

        public ITaskWorker Create()
        {
            return new TaskWorker();
        }

        public void Delete(ITaskWorker entity)
        {
            TaskWorker taskWorker = _context.TaskWorkers.SingleOrDefault(tw => tw.Id == entity.Id);
            _context.TaskWorkers.DeleteObject(taskWorker);
        }

        public ITaskWorker Insert(ITaskWorker entity)
        {
            TaskWorker res = entity as TaskWorker;
            _context.TaskWorkers.AddObject(res);
            _manager.Save();
            return res;
        }
    }
}
